//
//  ZJKComposeView.swift
//  MicroBlog
//
//  Created by VAD on 16/4/25.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

import pop


class ZJKComposeView: UIView {
    
    //懒加载按钮数组
    lazy var menuButtons: [ZJKComposeMenuButton] = []
    
    //模型数组
    lazy var array: [ZJKComposeMenuItemInfo] = {
        return self.itemInfos()
        
    }()
    
    // 当前视图添加到的控制器
    var target: UIViewController?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        frame = UIScreen.mainScreen().bounds
        
        let image = UIImage.getScreenShot().applyLightEffect()
        let imageView = UIImageView(image: image)
        
        addSubview(imageView)
        
        // 添加 标语
        addSubview(sloganImage)
        
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        
        addMenuButtons()
        
    }
    
    // 添加菜单的按钮
    private func addMenuButtons(){
        
        // 0. 计算每一个按钮之间的横向间距
        let itemW: CGFloat = 80
        let itemH: CGFloat = 110
        let margin = (SCREENW - 3 * itemW)/4
        
        for (i,value) in array.enumerate() {
            
            // 添加按钮
            let button = ZJKComposeMenuButton(textColor: UIColor.darkGrayColor(), fontSize: 14)
            // 点击事件
            button.addTarget(self, action: "menuButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            // 绑定tag以便获取数据
            button.tag = i
            button.setTitle(value.title, forState: UIControlState.Normal)
            button.setImage(UIImage(named: value.icon!), forState: UIControlState.Normal)
            button.frame.size = CGSize(width: itemW, height: itemH)
            addSubview(button)
            menuButtons.append(button)
            // 调整位置
            // 0. 计算列数与行数
            let col = i % 3
            let row = i / 3
            
            // 1. 计算x值
            button.frame.origin.x = CGFloat(col) * itemW + CGFloat(col + 1) * margin
            // 2. 计算y值
            button.frame.origin.y = CGFloat(row) * itemH + CGFloat(row) * 10 + SCREENH
        }
    }
    
    // 读取按钮内容数据
    private func itemInfos() -> [ZJKComposeMenuItemInfo] {
        
        
        // 从 plist 里面读取数据
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path)!
        
        
        // 初始化一个临时数组，记录字典转模型结果
        var tempArray: [ZJKComposeMenuItemInfo] = []
        for value in array {
            let info = ZJKComposeMenuItemInfo(dict: value as! [String : AnyObject])
            tempArray.append(info)
        }
        return tempArray
    }

    
    // MARK: - 提供给外界的方法
    
    func show(target: UIViewController?) {
        target?.view.addSubview(self)
        // 记录外界传入的target
        self.target = target
    }

    
    override func didMoveToSuperview() {
        
        super.didMoveToSuperview()
        
        for (index,value) in menuButtons.enumerate(){
            
            animation(value, index: index, isUp: true)
            
        }
    }
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        
        // 执行动画
        for (index,value) in menuButtons.reverse().enumerate() {
            animation(value, index: index, isUp: false)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
        
    }

    
    
    func animation(value: UIView, index: Int, isUp: Bool){
        // 1. 初始化动画的对象
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        // 2. 指定动画要执行的结束位置
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? -350 : 350)))
        // 3. 设置动画的一些属性
        anim.springSpeed = 10
        
        anim.springBounciness = 8
        
        anim.beginTime = Double(index) * 0.025 + CACurrentMediaTime()
        
        value.pop_addAnimation(anim, forKey: nil)
        
    }
    
    @objc private func menuButtonClick(button: UIButton) {
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.menuButtons {
                value.alpha = 0.01
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.01, 0.01)
                }
            }
            }) { (_) -> Void in
                // 取到模型
                let model = self.array[button.tag]
        
                let type = NSClassFromString(model.className!)! as! UIViewController.Type
                let vc = type.init()
                // 怎么取
                self.target?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
        }
    }


    
    // 标语
    private lazy var sloganImage = UIImageView(image: UIImage(named: "compose_slogan"))

}
